const cluster = require('cluster');
const https = require('https');
const proxy = require('request');
const fs = require('fs');
const options = {
  key: fs.readFileSync('keys/privatekey.pem'),
  cert: fs.readFileSync('keys/certificate.pem')
};
if (cluster.isMaster) {
  // Keep track of http requests
  let numReqs = 0;
  setInterval(() => {
    console.log(`numReqs = ${numReqs}`);
  }, 1000);
  // Count requests
  function messageHandler(msg) {
    if (msg.cmd && msg.cmd === 'notifyRequest') {
      numReqs += 1;
    }
  }
  const numCPUs = require('os').cpus().length;
  for (let i = 0; i < numCPUs; i++) {
    cluster.fork();
  }
  for (const id in cluster.workers) {
    cluster.workers[id].on('message', messageHandler);
  }

} else {
  const server = https.createServer(options, (req, res) => {
     if("/favicon.ico" == req.url) {
      return;
     }
     const ip = req.socket.remoteAddress;
     const port = req.socket.remotePort;
     const url = req.url;
     console.log(`Your IP address is ${ip} and your source port is ${port}.`);
     console.log(`req url = ${url}`);
     proxy(('https://maps.googleapis.com'+url), function (error, response, body) {
       if (!error && response.statusCode == 200) {
             const headers = response.headers;
             for (var key in headers) {
                 res.setHeader(key, headers[key]);
             }
             res.end(body);
         }
     });
     // notify master about the request
     process.send({ cmd: 'notifyRequest' });
  });
  server.on('clientError', (err, socket) => {
    socket.end('HTTP/1.1 400 Bad Request\r\n\r\n');
  });
  console.log("Https server listening on port 3000.");
  server.listen(3000);
}